package no.ffi.gismoidm.servicestubs;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author anders
 */
public class CaServiceTest {
    
    static String serviceURL = "http://192.168.0.102:8080/IdmServlets/Ca";

    public static void mainx(String[] args) throws Exception {
        IdPServiceHost sh = new IdPServiceHost();
        FileInputStream fis = new FileInputStream("/home/anders/Dropbox/tpmstuff/LKRequest.file");
        ObjectInputStream oid = new ObjectInputStream(fis);
        Object o = oid.readObject();
        oid.close();
        Object o2 = goHTTP(serviceURL,o);
        System.out.println(o2);
    }
    
    
    public static void main(String[] args) throws Exception {  
        // Read file content
        FileInputStream fis = new FileInputStream("/home/anders/Dropbox/tpmstuff/PCAReqSerialized.file");
        ObjectInputStream ois = new ObjectInputStream(fis);
        Object o = ois.readObject();
        ois.close();
        
        Object o2 = goHTTP(serviceURL,o);
        
        FileOutputStream fos = new FileOutputStream("/home/anders/Dropbox/tpmstuff/PCARespSerialized.filex");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(o2);
        oos.close();
        System.out.println(o2);
    }
    
    private static Object goHTTP(String url, Object o) throws IOException,ClassNotFoundException {
        URL serviceUrl = new URL(url);
        HttpURLConnection urlc = (HttpURLConnection)serviceUrl.openConnection();

        urlc.setRequestMethod("POST");
        urlc.setDoInput(true);
        urlc.setDoOutput(true);
        urlc.setRequestProperty("Content-Type", "application/x-javaobject");
        OutputStream os = urlc.getOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(o);
        oos.close();
        // Now wait for response
        // Error/timeout conditions throws a SocketException
        InputStream is = urlc.getInputStream();
        ObjectInputStream ois = new ObjectInputStream(is);
        Object o2 = ois.readObject();
        return o2;
    }
    
    

    
    
}
